<template>
    <div class="common-layout">
        <el-container>
            <el-header style="height: 100px;">
                <!-- 面包屑 -->
                <el-breadcrumb :separator-icon="ArrowRight" style="margin-bottom: 20px;">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item :to="{ path: '/' }">流程引擎</el-breadcrumb-item>
                    <el-breadcrumb-item>表单管理</el-breadcrumb-item>
                </el-breadcrumb>

                <!-- 查询条件 -->
                <el-card>
                    <el-row>
                        <el-col :span="5">
                            <el-text>表单名称:</el-text>
                            <el-input placeholder="请输入表单名称" v-model="searchForm.formName"
                                style="width: 70%;margin-left: 10px;" />
                        </el-col>
                        <el-col :span="5">
                            <el-text> 表单分类:</el-text>
                            <el-select v-model="searchForm.typeId" placeholder="请选择表单分类" style="width: 70%;" clearable>
                                <el-option v-for="item in formTypeDropData" :key="item.typeId" :label="item.typeName"
                                    :value="item.typeId" />
                            </el-select>
                        </el-col>
                        <el-col :span="5">
                            <el-text> 行业名称：</el-text>
                            <el-select v-model="searchForm.professionalId" placeholder="请选择行业名称" style="width: 70%;"
                                clearable>
                                <el-option label="行政" value="1" />
                                <el-option label="公安" value="2" />
                                <el-option label="消防" value="3" />
                                <el-option label="交通" value="4" />
                            </el-select>
                        </el-col>
                        <el-col :span="4">
                            <el-button type="primary" @click="handleSearch">搜索</el-button>
                            <el-button @click="handleReset">重置</el-button>
                        </el-col>
                    </el-row>
                </el-card>

            </el-header>
            <!-- 表单数据列表 -->
            <el-main>
                <el-card>
                    <el-row>
                        <el-col>
                            <el-button type="primary" @click="dialogFormVisible = true"> 添加</el-button>
                        </el-col>
                    </el-row>
                    <el-table :data="tableData" stripe style="width: 100%">
                        <el-table-column prop="FormNo" label="表单编号" />
                        <el-table-column prop="FormName" label="表单名称" />
                        <el-table-column prop="TypeName" label="表单分类" />
                        <el-table-column label="所属行业">
                            <template #default="scope">
                                {{ getIndustryLabel(scope.row.professionalId) }}
                            </template>
                        </el-table-column>

                        <el-table-column>
                            <template #default="scope">
                                <el-button type="warning" @click="handleEdit(scope.row)">编辑</el-button>
                                <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
                                <el-button type="primary" @click="handleFormDetailSetting(scope.row)">添加表单明细</el-button>
                            </template>
                        </el-table-column>

                    </el-table>

                    <Pagination :current-page="searchForm.pageIndex" :page-size="searchForm.pageSize"
                        :total-count="searchForm.totalCount" :total-page="searchForm.totalPage"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </Pagination>

                </el-card>
            </el-main>
        </el-container>
    </div>

    <!-- 添加表单弹出框 -->
    <el-dialog v-model="dialogFormVisible" title="添加表单数据" width="500">
        <el-form :model="inputData">
            <el-form-item label="表单名称" :label-width="formLabelWidth">
                <el-input v-model="inputData.formName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="表单分类" :label-width="formLabelWidth">
                <el-select v-model="inputData.typeId" placeholder="请选择表单分类" style="width: 70%;" clearable>
                    <el-option v-for="item in formTypeDropData" :key="item.typeId" :label="item.typeName"
                        :value="item.typeId" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleSubmit">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

       <!-- 表单明细对话框 -->
       <el-dialog v-model="dialogFormDetailVisible" title="表单明细操作" width="1600">

        <el-row>
            <el-col>
                <el-button type="primary" @click="handleFormDetailRowAdd"> 添加</el-button>
            </el-col>
        </el-row>

        <el-table :data="formDetailData">
            <el-table-column type="index" label="行号" width="180" />
            <el-table-column property="fieldName" label="字段名称">
                <template #default="scope">
                    <el-input v-model="scope.row.fieldName" />
                </template>
            </el-table-column>
            <el-table-column property="fieldDescription" label="字段描述">
                <template #default="scope">
                    <el-input v-model="scope.row.fieldDescription" />
                </template>
            </el-table-column>
            <el-table-column property="fieldType" label="字段类型">
                <template #default="scope">
                    <el-select v-model="scope.row.fieldType" placeholder="请选择字段类型" style="width: 90%;" clearable>
                        <el-option label="字符串" value="string" />
                        <el-option label="整型" value="int" />
                        <el-option label="浮点" value="float" />
                        <el-option label="布尔" value="bool" />
                        <el-option label="日期" value="date" />
                        <el-option label="时间" value="datetime" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column property="fieldControl" label="控件类型">
                <template #default="scope">
                    <el-select v-model="scope.row.fieldControl" placeholder="请选择控件类型" style="width: 90%;" clearable>
                        <el-option label="文本框" value="text" />
                        <el-option label="下拉框" value="select" />
                        <el-option label="单选框" value="radio" />
                        <el-option label="复选框" value="checkbox" />
                        <el-option label="日期选择器" value="date" />
                        <el-option label="时间选择器" value="datetime" />
                        <el-option label="文本域" value="textarea" />
                    </el-select>
                </template>
            </el-table-column>
            
            <el-table-column property="fieldProperties" label="控件属性" width="350%">
                <template #default="scope">
                    <el-input v-model="scope.row.fieldProperties" style="width: 50%;margin-right: 10px;" disabled />
                    <el-button type="primary" @click="handleFormDetailPropertiesSetting(scope.row)">设置</el-button>
                    <el-button type="danger" @click="handleFormDetailRowDelete(scope.row)">清空</el-button>
                </template>
            </el-table-column>
            <el-table-column property="fieldDefaultValue" label="默认值">
                <template #default="scope">
                    <el-input v-model="scope.row.fieldDefaultValue" />
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="120">
                <template #default="scope">
                    <el-button type="danger" @click="handleFormDetailRowDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormDetailVisible = false">取消</el-button>
                <el-button type="primary" @click="handleFormDetailSave()">确认</el-button>
            </div>
        </template>

    </el-dialog>

      <!-- 表单明细空间属性弹出框 -->
      <el-dialog v-model="dialogFormDetailPropertiesVisible" title="控件属性操作" width="700">
        <el-row>
            <el-col>
                <el-button type="primary" @click="handleFormDetailPropertiesRowAdd"> 添加</el-button>
            </el-col>
        </el-row>
        <el-table :data="formDetailPropertieData">
            <el-table-column type="index" label="行号" />
            <el-table-column property="value" label="属性名称">
                <template #default="scope">
                    <el-input v-model="scope.row.label" />
                </template>
            </el-table-column>
            <el-table-column property="value" label="属性值">
                <template #default="scope">
                    <el-input v-model="scope.row.value" />
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="120">
                <template #default="scope">
                    <el-button type="danger" @click="handleFormDetailPropertiesRowDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormDetailPropertiesVisible = false">取消</el-button>
                <el-button type="primary" @click="handleFormDetailPropertiesSave()">确认</el-button>
            </div>
        </template>

    </el-dialog>


  

</template>


<script lang="ts" setup>
import { ArrowRight, CirclePlus, Search } from '@element-plus/icons-vue'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import Pagination from '@/components/Pagination.vue'
import { addFormInfo,getFormInfo,deleteFormInfo,updateFormInfo  } from '@/api/formInfo'

//定义下拉框数据的接口
interface FormTypeDropData {
    typeId: string
    typeName: number
}


//定义表单明细数据的接口
interface FormDetailData {
    formDetailId: number
    formId: number
    fieldName: string
    fieldDesc: string
    fieldType: string
    fieldControl: string
    fieldProperties: string
    fieldDefaultValue: string
}

//定义表单明细控件属性数据的接口
interface FormDetailPropertiesData {
    value: string
    label: string
}

//定义查询条件
const searchForm = reactive({
    formName: '',
    typeId: null,
    professionalId: null,
    pageIndex: 1,
    pageSize: 3,
    totalCount: 0,
    totalPage: 0
})

//定义行业数据
const professionalData = ref([
    { label: '行政', value: 1 },
    { label: '公安', value: 2 },
    { label: '消防', value: 3 },
    { label: '交通', value: 4 }
])

//初始化表单数据
const initInputForm = reactive({
    formId: null,
    formName: '',
    typeId: ''
})

//定义表格数据
const tableData = ref([])
//定义弹出框
const dialogFormVisible = ref(false)
//定义表单明细弹出框
const dialogFormDetailVisible = ref(false)
//定义表单明细控件属性弹出框
const dialogFormDetailPropertiesVisible = ref(false)
//定义空间宽度
const formLabelWidth = ref('120px')
//定义表单分类下拉框数据
const formTypeDropData = ref<FormTypeDropData[]>([])
//定义表单数据
const inputData = reactive({ ...initInputForm })

//定义表单明细数据
const formDetailData = ref<FormDetailData[]>([])
//定义表单明细控件属性数据
const formDetailPropertieData = ref<FormDetailPropertiesData[]>([])

//定义当前正在操作的明细 ID
const currentFormDetailId = ref(0)

//#region 表单相关操作  

// 获取行业标签
const getIndustryLabel = (id: number) => {
    const industry = professionalData.value.find(item => item.value === id)
    return industry ? industry.label : '未知行业'
}

//分页
const handleSizeChange = (val: number) => {
    searchForm.pageSize = val;
    handleSearch()
}
const handleCurrentChange = (val: number) => {
    searchForm.pageIndex = val;
    handleSearch()
}

//重置查询条件
const handleReset = () => {
    searchForm.formName = ''
    searchForm.typeId = null
    searchForm.professionalId = null
}

//编辑表单信息
const handleEdit = async (row: any) => {

    console.log(row)

    // 填充表单数据
    Object.assign(inputData, row)

    // 打开编辑弹出框
    dialogFormVisible.value = true
}

//弹出框的取消
const handleCancel = () => {
    // 关闭弹出框
    dialogFormVisible.value = false
    //重置表单数据
    Object.assign(inputData, initInputForm)
}

//提交事件
const handleSubmit = async () => {
    if (inputData.formId) {
        // 如果存在 typeId，说明是编辑
        await updateFormInfo(inputData)
        ElMessage.success("修改表单分类成功")
    } else {
        // 否则是新增
        await addFormInfo(inputData)
        ElMessage.success("新增表单分类成功")
    }

    // 重新加载表格数据
    handleSearch()
    // 重置表单数据
    Object.assign(inputData, initInputForm)
    // 关闭弹出框
    dialogFormVisible.value = false
}


//查询表单 表单数据列表
const handleSearch = async () => {
    
    // 发送请求获取数据
    const res = await getFormInfo(searchForm)
    console.log(res);
    tableData.value = res.data.Result.Data
    searchForm.totalCount = res.data.Result.TotalCount
    searchForm.totalPage = res.data.Result.TotalPage
}

//删除表单信息
const handleDelete = async (row: any) => {
    // 确认删除
    ElMessageBox.confirm('确定删除该表单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 删除数据
        await deleteFormInfo(row.formId)
        ElMessage.success("删除表单成功")
        // 重新加载表格数据
        handleSearch()
    })
}

onMounted(()=>{
    handleSearch();
})

//#endregion

//#region 表单明细相关操作

const handleFormDetailSetting = async (row: any) => {
    //显示表单明细对话框
    dialogFormDetailVisible.value = true

    //去后台查询，如果没有数据的话 生成 3 个默认的空数据 
    //如果有数据 就加载后台的数据

    //生成三个默认的空数据
    formDetailData.value = [
        { formDetailId: 1, formId: row.formId, fieldName: '', fieldDesc: '', fieldType: '', fieldControl: '', fieldProperties: '', fieldDefaultValue: '' },
        { formDetailId: 2, formId: row.formId, fieldName: '', fieldDesc: '', fieldType: '', fieldControl: '', fieldProperties: '', fieldDefaultValue: '' },
        { formDetailId: 3, formId: row.formId, fieldName: '', fieldDesc: '', fieldType: '', fieldControl: '', fieldProperties: '', fieldDefaultValue: '' }
    ]
}

//表单明细添加一个空行
const handleFormDetailRowAdd = () => {

    //添加一行数据
    formDetailData.value.push({ formDetailId: generateFakeId(), formId: 0, fieldName: '', fieldDesc: '', fieldType: '', fieldControl: '', fieldProperties: '', fieldDefaultValue: '' })
}

//表单删除一个空行
const handleFormDetailRowDelete = (row: any) => {
    //删除一行数据
    const index = formDetailData.value.indexOf(row)
    if (index > -1) {
        formDetailData.value.splice(index, 1)
    }
}

//保存表单明细数据
const handleFormDetailSave = async () => {
    //去除空数据
    formDetailData.value = formDetailData.value.filter(item => item.fieldName !== '' && item.fieldDesc !== '' && item.fieldType !== '' && item.fieldControl !== '')

    //保存数据到后台
    console.log(formDetailData.value)

    var params = {
        formDetails: formDetailData.value
    }

    await fetchFormDetailSave(params)
    ElMessage.success("保存表单明细成功")

    //关闭弹出框
    dialogFormDetailVisible.value = false
}

//#endregion

//#region 表单明细控件属性相关操作

//表单明细控件属性添加一个空行
const handleFormDetailPropertiesRowAdd = () => {
    //添加一行数据
    formDetailPropertieData.value.push({ value: '', label: '' })
}
//表单明细控件属性删除一个空行
const handleFormDetailPropertiesRowDelete = (row: any) => {
    //删除一行数据
    const index = formDetailPropertieData.value.indexOf(row)
    if (index > -1) {
        formDetailPropertieData.value.splice(index, 1)
    }
}

const handleFormDetailPropertiesSetting = (row: FormDetailData) => {

    //设置当前正在操作的明细 ID
    currentFormDetailId.value = row.formDetailId

    //如果有数据 就加载后台的数据
    if (row.fieldProperties) {

        //将字符串转换为对象
        formDetailPropertieData.value = JSON.parse(row.fieldProperties)

        //如果数据不足三条则补充到三条
        if (formDetailPropertieData.value.length < 3) {
            for (let i = formDetailPropertieData.value.length; i < 3; i++) {
                formDetailPropertieData.value.push({ value: '', label: '' })
            }
        }


    } else {
        //如果没有数据 就生成三个默认的空数据
        formDetailPropertieData.value = [
            { value: '', label: '' },
            { value: '', label: '' },
            { value: '', label: '' }
        ]
    }


    //打开表单明细控件属性弹出框
    dialogFormDetailPropertiesVisible.value = true
}

//保存表单明细控件属性数据
const handleFormDetailPropertiesSave = () => {

    //除去formDetailPropertieData里的空数据
    formDetailPropertieData.value = formDetailPropertieData.value.filter(item => item.label !== '' && item.value !== '')

    //保存数据到明细里
    const formDetail = formDetailData.value.find(item => item.formDetailId === currentFormDetailId.value)
    if (formDetail && formDetailPropertieData.value.length > 0) {
        formDetail.fieldProperties = JSON.stringify(formDetailPropertieData.value)
    }

    //关闭弹出框
    dialogFormDetailPropertiesVisible.value = false
}

//#endregion

//生成 fakeID
const generateFakeId = () => {
    return Math.floor(Math.random() * 1000000000)
}

</script>

